﻿
using System;
using System.Reflection;

namespace MNH.WebApps.Common.Helpers.JqGrid
{
  public static class ReflectionHelper
  {
    public static Type FindFieldType(this Type type, string fieldName, string parent = "", int dumpLevel = 3)
    {
      foreach (PropertyInfo propertyInfo in type.GetProperties())
      {
        if (parent + propertyInfo.Name == fieldName)
          return propertyInfo.PropertyType;
        if (parent.Split('.').Length <= dumpLevel && ReflectionHelper.isNestedProperty(propertyInfo.PropertyType))
        {
          Type fieldType = ReflectionHelper.FindFieldType(propertyInfo.PropertyType, fieldName, propertyInfo.Name + ".", 3);
          if (fieldType != (Type) null)
            return fieldType;
        }
      }
      return (Type) null;
    }

    private static bool isNestedProperty(Type type)
    {
      if (type.Assembly.FullName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase))
        return false;
      else
        return (type.IsClass || type.IsInterface) && (!type.IsValueType && !string.IsNullOrEmpty(type.Namespace)) && !type.Namespace.StartsWith("System.", StringComparison.OrdinalIgnoreCase);
    }
  }
}
